using System;

namespace SpatialApp;

internal class InterpolateBuf
{
	public static double[] Interpolate(double[] buf, int width, int height, int nwidth, int nheight)
	{
		try
		{
			double[] nBuf = new double[nwidth * nheight];
			for (int h = 0; h < nheight; h++)
			{
				for (int w = 0; w < nwidth; w++)
				{
					double x = (double)(width - 1) * 1.0 / (double)(nwidth - 1) * (double)w;
					double y = (double)(height - 1) * 1.0 / (double)(nheight - 1) * (double)h;
					int xx = (int)x;
					int yy = (int)y;
					double fx = x - (double)xx;
					double fy = y - (double)yy;
					if (Math.Abs(fx - 0.0) < 1E-06 && x > 0.0)
					{
						xx--;
						fx = 1.0;
					}
					if (Math.Abs(fy - 0.0) < 1E-06 && y > 0.0)
					{
						yy--;
						fy = 1.0;
					}
					double f0 = buf[yy * width + xx];
					double f2 = buf[yy * width + xx + 1];
					double f = buf[(yy + 1) * width + xx];
					double f3 = buf[(yy + 1) * width + xx + 1];
					nBuf[h * nwidth + w] = f0 * (1.0 - fx) * (1.0 - fy) + f2 * fx * (1.0 - fy) + f * (1.0 - fx) * fy + f3 * fx * fy;
				}
			}
			return nBuf;
		}
		catch (Exception ex)
		{
			Console.WriteLine("Interpolate error.");
			Console.WriteLine(ex.Message);
		}
		return null;
	}
}
